//
//  JwUUID.m
//  JwPack
//
//  Created by 陈警卫 on 2024-07-31.
//

#import "JwUUID.h"
#import <UIKit/UIKit.h>
#import <AdSupport/AdSupport.h>
#import "JwKeychain.h"
#import "JwDevice.h"

@implementation JwUUID

/// 随机uuid 
/// 每次都不一样
+ (NSString *)uuidRandomString {
    CFUUIDRef uuid_ref = CFUUIDCreate(NULL);
    CFStringRef uuid_string_ref = CFUUIDCreateString(NULL, uuid_ref);
    NSString *uuid = [NSString stringWithString:(__bridge NSString *)uuid_string_ref];
    CFRelease(uuid_ref);
    CFRelease(uuid_string_ref);
    return [uuid uppercaseString];
}

/// uuidIDFV
/// 卸载安装后不一样
/// 在同一设备中 该供应商的所有 App 的 IDFV 相同 应用删除该供应商所有 App 时 重新下载 App IDFV 发生变化
+ (NSString *)uuidIDFVString {
    return [UIDevice currentDevice].identifierForVendor.UUIDString;
}

/// uuidIDFA
/// 不会因为应用卸载改变
/// 但是用户在设置-隐私-广告里面限制广告跟踪后会变成 @"00000000-0000-0000-0000-000000000000"
/// 重新打开后会变成另一个 还原广告标识符也会变
+ (NSString *)uuidIDFAString {
   return [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
}

/// 唯一UUID
/// Keychain + IDFA
+ (NSString *)uuidByKeychain {
    NSString *key = @"jw.uuid.idfa";
    key = [NSString stringWithFormat:@"%@.%@", [JwDevice bundleID], key];
    NSString *strUUID = (NSString *)[JwKeychain load:key];

    if ([strUUID isEqualToString:@""] || !strUUID) {
        strUUID = [self uuidIDFAString];
        if (strUUID.length == 0 || [strUUID isEqualToString:@"00000000-0000-0000-0000-000000000000"]) {
            CFUUIDRef uuidRef = CFUUIDCreate(kCFAllocatorDefault);
            strUUID = (NSString *)CFBridgingRelease(CFUUIDCreateString(kCFAllocatorDefault, uuidRef));
            CFRelease(uuidRef);
        }
        [JwKeychain save:key data:strUUID];
    }
    return strUUID;
}


@end
